﻿using DOM;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using NHibernate.Context;

namespace DBinit
{
    /// <summary>
    /// the class is being used to generate the database
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            var persistenceModel = AutoMap.AssemblyOf<Customer>()
                        .Setup(s =>
                        {
                            //s.IsBaseType = type => type == typeof(EntityBase);

                        })
                        .IgnoreBase<EntityBase>()
                        .Conventions.Add<PrimaryKeyConvention>();
            //persistenceModel.WriteMappingsTo(@"c:\projects\testin research\NHibernateSampleMVC3\DOM\DOM.hbm.xml");
            ISessionFactory fac = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(p => p.FromConnectionStringWithKey("ConnString")))
                .Mappings(m => m.AutoMappings.Add(persistenceModel))
                .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();
            using (var session = fac.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    session.Save(new Users { Username = "admin", Password = MD5Hash("admin"), isActive = true, LastLogin = DateTime.Now, DisplayName = "Admin Admin" });
                    tx.Commit();
                }
            }
            
        }

        private static void BuildSchema(Configuration config)
        {
            // this NHibernate tool takes a configuration (with mapping info in)
            // and exports a database schema from it
            new SchemaExport(config)
                .Create(true, true);
        }

        public static string MD5Hash(string text)
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            //compute hash from the bytes of text
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));

            //get hash result after compute it
            byte[] result = md5.Hash;

            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                //change it into 2 hexadecimal digits
                //for each byte
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }
    }
}
